package com.spark.shiro.web;

import com.spark.shiro.bean.ResponseEntity;
import com.spark.shiro.entity.User;
import com.spark.shiro.service.UserService;
import com.spark.shiro.util.CryptographyUtil;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * Created by tyd on 2017-10-28.
 */
@Controller
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    @RequestMapping(value = "/toLogin", method = RequestMethod.GET)
    public String toLogin() {
        return "/login";
    }

    @RequestMapping(value = "/login", method = RequestMethod.POST)
    public String login(HttpServletRequest request,
                        @RequestParam("userName") String userName,
                        @RequestParam("password") String password) {

        UsernamePasswordToken token = new UsernamePasswordToken(userName, CryptographyUtil.md5(password, "spark"));

        Subject subject = SecurityUtils.getSubject();
        try {
            subject.login(token);
        } catch (AuthenticationException e) {
            request.setAttribute("errorMsg", "身份认证失败");
            return "/login";
        }
        return "/success";
    }

    @RequestMapping("/list")
    @ResponseBody
    public ResponseEntity<User> list(@RequestParam("currentPage") int currentPage,
                                     @RequestParam(value = "userName", required = false) String userName) {
        return userService.getUserListByPage(userName,currentPage);
    }

    @RequestMapping("/unauthorized")
    public String authorizerd() {
        return "/unauthorizedUrl";
    }
}
